package com.startest.sms.utils;

import com.sun.mail.util.MailSSLSocketFactory;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

/**
 * Created by cly on 2018/12/10.
 */
public class MailUtil implements Runnable{
    private String email;//收件人邮箱
    private String code;//激活码

    public MailUtil(String email, String code) {
        this.email = email;
        this.code = code;
    }

    @Override
    public void run() {
        String from = "1925965008@qq.com";//发件人邮箱
        String host = "smtp.qq.com";//指定发送邮件服务器

        Properties properties = System.getProperties();
        properties.setProperty("mail.smtp.host",host); // 设置邮件服务器
        properties.setProperty("mail.smtp.auth","true");//打开认证

        try {
            MailSSLSocketFactory factory = new MailSSLSocketFactory();
            factory.setTrustAllHosts(true);
            properties.put("mail.smtp.ssl.enable","true");
            properties.put("mail.smtp.ssl.socketFactory", factory);

            Session session = Session.getDefaultInstance(properties, new Authenticator() {
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication("1925965008@qq.com","tdsvtaaewnbyebej");//发件人邮箱账号，授权码
                }
            });
            //创建邮件对象
            MimeMessage message = new MimeMessage(session);
            //设置发件人
            message.setFrom(new InternetAddress(from));
            //设置接收人
            message.setRecipient(Message.RecipientType.TO,new InternetAddress(email));
            //设置邮件主题
            message.setSubject("账号激活");
            //设置邮件内容
            String content = "<html><head></head><body><h1>这是一封激活邮件,激活请点击以下链接</h1><h3><a href='http://localhost:8080/api/luss/v1/user/emailActive?code="
                    + code + "'>http://localhost:8080/api/luss/v1/user/emailActive?code=" + code
                    + "</a></h3></body></html>";
            message.setContent(content,"text/html;charset=UTF-8");
            // 发送邮件
            Transport.send(message);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
